import { defineStore } from 'pinia'
import axios from 'axios'

// 定义API响应类型
interface GameState {
  board: string[]
  currentPlayer: 'X' | 'O'
  gameActive: boolean
  winner: string | null
}

const api = axios.create({
  baseURL: 'http://localhost:3000/api',
  timeout: 1000
})

export const useGameStore = defineStore('game', {
  state: () => ({
    board: Array(9).fill(''),
    currentPlayer: 'X' as 'X' | 'O',
    gameActive: true,
    winner: null as string | null,
    winningCells: [] as number[] // 修正类型声明
  }),
  actions: {
    async initializeGame() {
      try {
        const response = await api.post<{ gameId: string }>('/games')
        return response.data.gameId
      } catch (error) {
        console.error('Failed to initialize game:', error)
        throw error
      }
    },
    async makeMove(cellIndex: number) {
      if (!this.gameActive || this.board[cellIndex] !== '') return

      try {
        const response = await api.post<GameState>('/games/move', {
          cellIndex,
          currentPlayer: this.currentPlayer,
          board: this.board
        })

        this.board = response.data.board
        this.currentPlayer = response.data.currentPlayer
        this.gameActive = response.data.gameActive
        this.winner = response.data.winner
        this.checkWinningCells()
      } catch (error) {
        console.error('Failed to make move:', error)
        throw error
      }
    },
    checkWinningCells() {
      if (!this.winner) {
        this.winningCells = []
        return
      }

      const winPatterns: number[][] = [
        [0, 1, 2], [3, 4, 5], [6, 7, 8], // 行
        [0, 3, 6], [1, 4, 7], [2, 5, 8], // 列
        [0, 4, 8], [2, 4, 6]             // 对角线
      ]

      for (const pattern of winPatterns) {
        const [a, b, c] = pattern
        if (
          this.board[a] &&
          this.board[a] === this.board[b] &&
          this.board[a] === this.board[c]
        ) {
          this.winningCells = pattern
          break
        }
      }
    },
    resetGame() {
      this.board = Array(9).fill('')
      this.currentPlayer = 'X'
      this.gameActive = true
      this.winner = null
      this.winningCells = []
    }
  }
})